<template>
  <view style="padding-bottom:10px">
    <template v-if="length>0&&!loading">
      <scroll-view scroll-x="true">
      <view :class="carType.length>4?'top-list':'top-list top-fixed'">
        <view
          v-for="(item,index) in carType"
          :key="index"
          class="top-item"
          @tap="currentTap(item,index)"
        >
          <image :src="soonImg+item.iconUrl+'?x-oss-process=style/w144'" class="img" />
          <view :class="index==active?'line active':'line'"></view>
          <view class="p1">{{item.name}}</view>
        </view>
      </view>
      </scroll-view>
      <view v-for="(item,index) in posterUrl" :key="index">
        <image :src="soonImg+item" mode="widthFix" style="width:100%" />
      </view>
      <view class="detail-list">
        <view
          class="detail-item"
          v-for="(item,index) in detailList"
          :key="index"
          @tap="goDetail(item)"
        >
          <view
            class="detail-top"
            v-if="item.specialPreference!==''&&item.preferentialStrength!==''"
          >
            <text class="detail-top-p1">{{item.specialPreference}}</text>
            <image :src="imgUrl+'/carSale/sd.png'" class="detail-top-img" />
            <text class="detail-top-p2">{{item.preferentialStrength}}</text>
          </view>
          <view class="detail-content">
            <image :src="soonImg+item.logoUrl" class="detail-left" mode="widthFix" />
            <view class="detail-right">
              <view class="p2 one-line">{{item.name}}</view>
              <view class="p3 one-line" v-if="item.description!==''">{{item.description}}</view>
              <view class="p4" v-if="item.tags[0]">
                <text v-for="(entry,ele) in item.tags" :key="ele">{{entry}}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view class="btn" @tap="handleCar">未找到想要的车型？点我填写</view>
      <!-- <navigator
        url="/pages/commodityDetail/index?goodsNo=QY2111043700"
        open-type="redirect"
        hover-class="none"
        class="btn"
      >付定金
      </navigator>
      <view class="btn" @tap="go">付定金</view>-->
    </template>
    <template v-if="carType.length==0&&!loading">
      <view class="text-center">
        <image :src="imgUrl+'/carSale/empty.png'" class="emptyImg" mode="widthFix" />
        <view class="text-p1" style="color:#9B9B9B">暂无活动</view>
      </view>
    </template>
    <view v-if="!hasPhone" class="open-dialog">
      <image src="../../image/close.png" class="panel-box-close" @tap="hasPhone=true" />
      <view class="title text-center">提示</view>
      <view class="info">尚未获取手机号，无法获取想要车型</view>
      <button
        openType="getPhoneNumber"
        @GetPhoneNumber="onGetPhoneNumber"
        class="panel-box-btn"
        size="mini"
      >获取手机号</button>
    </view>
    <view class="panel-bg" v-if="!hasPhone||isAgree||isBottom"></view>
    <!--获取报价弹框-->
    <view class="bottom" v-if="isBottom" animation="animationData">
      <view class="title">获取底价</view>
      <image
        :src="imgUrl+'/close.png'"
        class="panel-box-close"
        @tap="isBottom=false"
        style="top:10px"
      />
      <view class="bottom-list">
        <text class="bottom-p1">您的称呼：</text>
        <input v-model="name" type="text" placeholder="请输入您的姓名" class="bottom-inp1" />
        <radio-group
          name="radio"
          size="mini"
          @change="radioChange"
          style="float:right;right:20px;position:absolute"
        >
          <label>
            <radio value="'先生'" checked />先生
          </label>
          <label>
            <radio value="女士" />女士
          </label>
        </radio-group>
      </view>
      <view class="bottom-list">
        <text class="bottom-p1">意向车型：</text>
        <input
          v-model="carName"
          type="text"
          placeholder="请输入您的意向车型"
          class="bottom-inp1"
          style="width:77%"
        />
      </view>
      <view class="bottom-list">
        <text class="bottom-p1">手机号：</text>
        <text v-if="!isClear">{{mobile|filterTel}}</text>
        <input v-model="mobile" type="number" placeholder="请输入手机号" class="bottom-inp1" v-else />
        <image :src="imgUrl+'/clone2.png'" class="bottom-img" @tap="mobile='';isClear=true" />
      </view>
      <view class="info">
        <checkbox @tap="handleAgreeChecked" :checked="agreeChecked" />
        <view @tap="isAgree=true;isBottom=false" style="display:inline-block">
          请您仔细阅读
          <text style="color:#01A0FE">《隐私协议》</text>
        </view>
      </view>
      <view class="btn" @tap="submit">获取报价</view>
    </view>
    <!--用户协议-->
    <view v-if="isAgree" class="open-dialog agree" style="z-index:999">
      <view class="title text-center" style="padding-bottom:4px">用户协议</view>
      <agreement id="agreements" />
      <view class="btn-box">
        <view class="btn1" @tap="agreeChecked=false;isAgree=false">不同意</view>
        <view class="btn2" @tap="agreeChecked=true;isAgree=false">同意</view>
      </view>
    </view>
  </view>
</template>
<script>
import Taro from "@tarojs/taro";
import "./home.less";
import { setGlobalData, getGlobalData } from "../../globalData.js";
import agreement from "./agreement.vue";
import { request } from "../../util/axios.js";
import bulterApi from "@souche2014/bulter-api";
const api = bulterApi({ partner: "IOParking" });
export default {
  name: "home",
  data() {
    return {
      apiBaseUrl: "https://api.cccarlife.com/api/cccl/mobile/v1", //请求头部
       // apiBaseUrl: "https://api-dev.mobile.charging.keji.io/api/cccl/mobile/v1", //请求头部（预生产）
      soonImg: "https://soonsmart.keji.io/", //接收的后台图片
      imgUrl: process.env.IOParking.IMG_URL, //静态资源图片
      loading: true,
      carType: [],
      detailList: [],
      currentCar: null,
      isBottom: false,
      posterUrl: "",
      isShow: false,
      hasPhone: true,
      mobile: "",
      isMobile: false,
      sex: "先生",
      agreeChecked: true,
      isAgree: false,
      active: 0,
      isScode: false,
      id: null,
      name: "",
      isClear: false,
      carName: "",
      shareId: null,
      length: 0,
      apiBaseInfo: process.env.IOParking.API_HOST //请求头部
    };
  },
  components: { agreement },
  filters: {
    //加密手机号
    filterTel(val) {
      if (val) {
        return val.substring(3, 0) + "****" + val.substring(7);
      }
    }
  },
  onShareAppMessage: function() {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ["shareAppMessage", "shareTimeline"]
    });
  },
  //用户点击右上角分享朋友圈
  onShareTimeline: function() {
    return {
      title: "活动页",
      query: {}
    };
  },
  onLoad: function(options) {
    console.log("参数:", options);
    let that = this;
    if (options.q) {
      let qrUrl = decodeURIComponent(options.q);
      that.cardId = that.getQueryString(qrUrl, "cardId");
      that.shareId = that.getQueryString(qrUrl, "shareId");
      console.log("参数解析cardId：",that.cardId,'shareId:',that.shareId)
      if (that.cardId) {
        that.isScode = true;
      } else {
        that.isScode = false;
      }
      api.bury("CPA_SHARE_SUCC");
    } else {
      that.cardId = options.cardId;
      if (that.cardId) {
        that.isScode = true;
      } else {
        that.isScode = false;
      }
      that.shareId=options.shareId
      //this.isScode = false;
    }
    if (!getGlobalData("openId")) {
        that.wx_login();
      } else {
        that.initData();
    }
    console.log('推荐人id：',that.shareId)
  },
  methods: {
    initData() {
      console.log("进入--------初始化数据");
      var that = this;
      that.loading = true;
      Taro.showLoading({
        title: "努力加载中"
      });
      Taro.request({
        url: this.apiBaseUrl + "/activity/alllist",
        data: {},
        method: "GET",
        success(res) {
          console.log(res.data);
          Taro.hideLoading();
          that.loading = false;
          if (res.data.isSuccess) {
            that.carType = res.data.data;
            that.length = that.carType.length;
            if (that.isScode) {
              console.log("扫码id", that.cardId);
              let isOk = false; //是否过期
              that.carType.forEach((item, index) => {
                if (item.id == that.cardId) {
                  that.posterUrl = that.carType[index].posterUrl.split(",");
                  that.currentCar = that.carType[index];
                  that.getDetailInfo(that.carType[index].id);
                  that.active = index;
                  isOk = true;
                }
              });
              if (!isOk) {
                //如果列表里面没有已经过期，跳转默认第一个
                Taro.navigateTo({
                  url: "../carSale/result?isout=1&shareId="+that.shareId
                });
              }
            } else {
              console.log("isScode为false");
              that.posterUrl = that.carType[0].posterUrl.split(",");
              that.currentCar = that.carType[0];
              that.getDetailInfo(that.carType[0].id);
            }
          }
        },
        fail() {
          that.loading = false;
          Taro.hideLoading();
          Taro.showToast({
            title: "接口请求错误",
            icon: "none"
          });
        }
      });
    },
    getDetailInfo(id) {
      console.log(id);
      var that = this;
      Taro.request({
        url: this.apiBaseUrl + "/car/boundlist",
        data: {
          activityId: id
        },
        method: "GET",
        success(res) {
          console.log(res.data);
          if (res.data.isSuccess) {
            that.detailList = res.data.data;
            that.detailList.forEach((element, index) => {
              that.detailList[index].tags = element.tag.split(",");
              //that.detailList[index].imageUrls = element.imageUrls.split(",");
            });
           api.bury("ZC_PAGE_ENTER", {
             inPageType:that.inPageType,
             activeCarId:id
           });
          }
        }
      });
    },
    handleCar() {
      var that = this;
      if (getGlobalData("mobile") == "" || !getGlobalData("mobile")) {
        that.hasPhone = false;
        return;
      } else {
        that.isBottom = true;
        that.mobile = getGlobalData("mobile");
        that.isClear = false;
        api.bury("ZC_PAGE_CLICK_CPA");
      }
    },
    goDetail(data) {
      if(this.shareId){
        Taro.navigateTo({
        url: "../carSale/detail?id=" + data.id + "&shareId=" + this.shareId
      });
      }else{
        Taro.navigateTo({
        url: "../carSale/detail?id=" + data.id
      });
      }
      
    },
    radioChange(e) {
      console.log(e);
      this.sex = e.detail.value;
    },
    currentTap(data, index) {
      this.posterUrl = data.posterUrl.split(",");
      this.active = index;
      this.getDetailInfo(data.id);

    },
    handleSex(e) {
      console.log(e);
    },
    submit() {
      var that = this;
      that.wx_login();
      if (!that.agreeChecked) {
        Taro.showToast({
          title: "请勾选协议",
          icon: "error",
          duration: 1000,
          mask: true
        });
        return;
      }
      let pattern = /^1[3456789]\d{9}$/;
      if (!pattern.test(that.mobile)) {
        Taro.showToast({
          title: "手机号不正确",
          icon: "error",
          duration: 1000,
          mask: true
        });
        return;
      }
      Taro.showLoading({
        title: "提交中",
        mask: true
      });
      let params = {
        name: that.name + that.sex,
        mobile: that.mobile,
        openId: getGlobalData("openId"),
        carId: 0,
        carName: that.carName,
        housekeeperId: that.shareId
      };
      Taro.request({
        url: this.apiBaseUrl + "/customerintention/create",
        data: params,
        method: "POST",
        success(res) {
          Taro.hideLoading();
          console.log(res.data);
          if (res.data.isSuccess) {
            Taro.navigateTo({
              url: "../carSale/result?shareId=" + that.shareId
            });
          }
        },
        fail() {
          Taro.hideLoading();
          Taro.showToast({
            title: "接口请求错误",
            icon: "none"
          });
        }
      });
    },
    handleAgreeChecked() {
      this.agreeChecked = !this.agreeChecked;
    },
    changePhone() {},
    wx_login() {
      var that = this;
      api
        .getUserInfo({
          scope: "all"
        })
        .then(resp => {
          if (resp.success) {
            console.log("authCode is：", resp.data);
            if (resp.data == "mock") {
              setGlobalData("openId", "oRPxj5ZrsZGRuxTa-UrzEBeLuv-s");
              setGlobalData("mobile", "17761643218");
              that.mobile = "17761643218";
              that.initData();
              return;
            }
            that.getInfos(resp.data);
          } else {
            console.log("err is ", resp.message, "err code is ", resp.code);
          }
        });
    },
    getInfos(authCode) {
      var that = this;
      Taro.request({
        url: that.apiBaseInfo + "/weixin/souchegetuser?authCode=" + authCode,
        data: {},
        header: {
          "content-type": "application/json" // 默认值
        },
        method: "GET",
        success(res) {
          console.log("获取用户信息：", res.data);
          if (res.data.isSuccess) {
            var userOpenId = res.data.data.openId;
            setGlobalData("openId", userOpenId);
            setGlobalData("mobile", res.data.data.phoneNum);
            console.log("准备进入initData函数");
            that.initData();
            that.mobile = res.data.data.phoneNum;
          } else {
            that.initData();
          }
        }
      });
    },
    onGetPhoneNumber({ detail }) {
      const { encryptedData, iv } = detail;
      console.log("phone打印:" + JSON.stringify(detail));

      if (encryptedData && iv) {
        this.authPhone(encryptedData, iv);
        this.hasPhone = true;
        Taro.showLoading({
          title: "授权中，请稍后",
          mask: true
        });
      }
    },
    authPhone(encryptedData, iv) {
      api
        .register({
          encryptedData: encryptedData,
          iv: iv,
          scope: "all"
        })
        .then(resp => {
          Taro.hideLoading();
          if (resp.success) {
            console.log("用户注册 ", resp.data);
            if (resp.data == "mock") {
              setGlobalData("mobile", "17761643218");
              this.mobile = getGlobalData("mobile")
                ? getGlobalData("mobile")
                : "";
              return;
            }
            this.getInfos(resp.data);
          } else {
            console.log("err is ", resp.msg, "err code is ", resp.code);
          }
        })
        .catch(e => {
          console.log(e);
        });
    },
    //解析链接方法
    getQueryString(url, name) {
      var reg = new RegExp("(^|&|/?)" + name + "=([^&|/?]*)(&|/?|$)", "i");
      var r = url.substr(1).match(reg);
      if (r != null) {
        return r[2];
      }
      return null;
    }
  }
};
</script>

